package com.example.sherlockzhong.plush_v2;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import com.example.sherlockzhong.plush_v2.Models.DataModel;
import com.example.sherlockzhong.plush_v2.Utils.StorageUtils;

import org.json.JSONArray;
import org.json.JSONTokener;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by xujiachong on 14-9-21.
 */
public class MainService extends Service {

    private int ssid = 0;

    private Context context;

    private Timer timer;
    private TimerTask timerTask;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        this.context = getApplicationContext();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        //this.CreateInform("您有新的PLUSH信息","PLUSH", this.ssid + "条未读消息",100);
        //this.dir = intent.getExtras().getString("dir");
        this.startReflash();
    }

    //创建通知
    public void CreateInform(String alert, String title, String detail, int no_id) {
        //定义一个PendingIntent，当用户点击通知时，跳转到某个Activity(也可以发送广播等)
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        //创建一个通知
        Notification notification = new Notification(R.drawable.logo, alert, System.currentTimeMillis());
        notification.setLatestEventInfo(context, title, detail, pendingIntent);
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        //用NotificationManager的notify方法通知用户生成标题栏消息通知
        NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nManager.notify(no_id, notification);//id是应用中通知的唯一标识
        //如果拥有相同id的通知已经被提交而且没有被移除，该方法会用更新的信息来替换之前的通知。
    }

    private void startReflash() {
        this.timer = new Timer();
        this.timerTask = new TimerTask() {
            @Override
            public void run() {
                MainService.this.getNews();
            }
        };
        this.timer.schedule(this.timerTask, 5 * 60 * 1000, 5 * 60 * 1000);
    }

    private void stopRefresh() {
        if (this.timer != null) {
            this.timer.cancel();
        }
        if (this.timerTask != null) {
            this.timerTask.cancel();
        }
    }

    @Override
    public void onDestroy() {
        this.stopRefresh();
        super.onDestroy();
    }

    private void getNews() {
        String text;
        JSONArray array = DataModel.refresh();
        if (array != null) {
            this.ssid = array.length();
            text = ssid + "条未读消息";
        } else {
            text = "点击查看未读消息";
        }
        if (array.length() > 0) {

            Constant.NEW_CARD_COUNT = array.length();

            String histroyString = StorageUtils.retrieveFromFile("HistoryData.json");
            try {
                JSONTokener jsonTokener = new JSONTokener(histroyString);
                JSONArray historyArray = (JSONArray) jsonTokener.nextValue();
                for (int i = 0; i < array.length(); i++) {
                    historyArray.put(array.get(i));
                }
                DataModel.saveHistoryData(historyArray);
            } catch (Exception e) {
                e.printStackTrace();
            }

            this.CreateInform("您有新的PLUSH消息", "PLUSH", text, 100);
        }
    }
}
